package com.bs.visitservice.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bs.visitservice.cache.impl.JedisLoginCache;
import com.bs.visitservice.common.OrderInfoQueueDisp;
import com.bs.visitservice.controller.seller.SellerInfoController;
import com.bs.visitservice.entity.OrderInfo;
import com.bs.visitservice.entity.OrderProduct;
import com.bs.visitservice.entity.ReceiverAddress;
import com.bs.visitservice.entity.Seller;
import com.bs.visitservice.service.*;
import com.bs.visitservice.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/user")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ReceiverAddressService receiverAddressService;
    @Autowired
    private JedisLoginCache jedisCacheManager;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private SellerService sellerService;
    /**
     * 分页查询订单信息 不包含已删除
     * @param cond
     * @return 返回订单信息及订单包含商品信息proList
     */
    @RequestMapping(value = "/orderInfoList",method = RequestMethod.POST)
    public Result queryOrderInfo(@RequestBody  Map cond){
        Long userNo =(Long) ThreadLocalUtil.get("loginNo");
        IPage page = ParamUtils.getPage(cond);
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserNo, userNo).ne(OrderInfo::getIsDel,"1").orderByDesc(OrderInfo::getDatatime);
        page = orderInfoService.pageMaps(page,wrapper);
        List<Map<String, Object>> res = page.getRecords();
        res.forEach(map->{
            Long orderNo = (Long)map.get("no");
            List<Map<String,Object>> proList = productService.queryOrderProduct(orderNo);
            ResultUtil.transfort(proList, getDictMap(), true);
            map.put("proList", proList);
            Long sellerNo  = (Long)map.get("sellerNo");
            Seller seller = sellerService.getById(sellerNo);
            map.put("sellerName",seller.getSellerName());
            map.put("sellerPhoto",seller.getPhoto());
            //设置地址信息
            Object o = map.get("receiveNo");
            if(o != null){
                Long rn = (Long)o;
                ReceiverAddress ra = receiverAddressService.getById(rn);
                map.put("receiveInfo",ra);
            }
        });
        ResultUtil.transfort(res, getDictMap(), true);
        Map<String,Object> result = new HashMap<>();
        result.put("total",page.getTotal());
        result.put("datas",res);
        return Result.success(result);
    }

    /**
     * 更新订单
     *  0 接单中，1 已接单，2已到达，3已完成，4已删除，5已取消
     * @param cond
     * @return
     */
    @RequestMapping(value = "/updateOrderInfo",method = RequestMethod.POST)
    public Result deleteOrderInfo(@RequestBody Map cond){
        Long orderNo = Long.valueOf((String)cond.get("orderNo"));
        Integer orderStatus = (Integer)cond.get("orderStatus");
        OrderInfo queryOrder = orderInfoService.getById(orderNo);
        if(orderNo == 5){
            if(queryOrder.getOrderStatus() > 0){
                return Result.error(null);
            }
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setNo(orderNo);
        if(orderStatus == 4){
            orderInfo.setIsDel("1");
        }else{
            orderInfo.setOrderStatus(orderStatus);
        }
        boolean isSuc = orderInfoService.updateById(orderInfo);
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 新增订单
     * @param cond
     * @return
     */
    @Transactional
    @RequestMapping(value = "/saveOrderInfo",method = RequestMethod.POST)
    public Result insertOrderInfo(@RequestBody Map cond){
        Long userNo =(Long) ThreadLocalUtil.get("loginNo");
        List<Map> proList = (ArrayList<Map>)cond.get("proList");
        OrderInfo orderInfo = (OrderInfo)ResultUtil.transObject(cond, OrderInfo.class);
        String orderNo = IdGeneratorUtil.getGuid();
        orderInfo.setOrderNo(orderNo);
        orderInfo.setDatatime(new Date());
        orderInfo.setOrderStatus(0);
        orderInfo.setUserNo(userNo);
        orderInfo.setIsDel("0");
        boolean isSuc1 = orderInfoService.save(orderInfo);
        List<OrderProduct> orderProList = new ArrayList<>();
        proList.forEach(pro->{
           OrderProduct op = (OrderProduct)ResultUtil.transObject(pro, OrderProduct.class);
           op.setOrderNo(orderInfo.getNo());
           orderProList.add(op);
        });
        boolean isSuc2= orderProductService.saveBatch(orderProList);
        if(isSuc1 && isSuc2){
            OrderInfoQueueDisp.orderInfoQueue.offer(orderInfo);
            return Result.success(null);
        }
        return Result.error(null);
    }


    /**
     * 获取列和字典值的映射关系
     * @return
     */
    private Map getDictMap(){
        Map<String,String> dictMap = new HashMap<>();
        dictMap.put("orderStatus","orderStatus");
        return dictMap;
    }
}
